#!/usr/bin/perl

##############################################################
#
#Purpose: To test if a set of hosts are alive
#
#Usage: get_alive_hosts.pl -f <file name> -n <num_tries = 1>
#
#Restrictions: Requires admin privileges
#
##############################################################

use strict 'vars';
package main;

use Getopt::Std;

use vars qw($opt_f);

#get command line options
getopts('f:');
if ($opt_f eq "") {
    die "Usage:  nslookup_hosts.pl -f <file name> -n <num_tries = 1>\n";
}

#go over the list of hosts
my %hosts = (), my %hostname = (), my $IP, my $host;
open HOSTFILE, $opt_f;
while ($host = <HOSTFILE>) {
    chomp $host;
    if ($host =~ /^\s*#/) {
	next;
    }
    $IP = my_gethostbyname($host);
    print "$host ";
    if ($IP eq "NULL") {
	print "LOOKUP_FAILED";
    } else {
	print "$IP";
    }
    print "\n";
}

#wrapper to gethostbyname
sub my_gethostbyname {
    my $hostname = @_[0];
    my ($name, $altnames, $addrtype, $len, @addrlist);
    my @addrbytes, my $realaddr;

    if (!(($name, $altnames, $addrtype, $len, @addrlist) 
    			= gethostbyname ($hostname))) {
	return "NULL";	                
    }

    @addrbytes = unpack("C4", $addrlist[0]);
    $realaddr = join (".", @addrbytes);
    return $realaddr;
}
